#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

//#define T 41
//#define M 5

typedef struct Person{
  int number;
  struct Person* pre;
  struct Person* next;
}Person;

int test_log_list(struct Person* head,struct Person* current);
int joseplus(struct Person* current,int number);

int T = 0;
int M = 0;

int main()
{  
   printf("请输入总数T\n");
   scanf("%d",&T);
   printf("请输入跳过数M\n");
   scanf("%d",&M);
   printf("T=%d,M=%d\n",T,M);
  
   struct Person* head = NULL;
   struct Person* pre = NULL;
   for (int i=1;i <= T; i++)
   {
      struct Person* p = (Person *) malloc(sizeof(struct Person));
      
      p->number = i;

      if (i == 1)
      {// 头部
         head = p;
      }
      if (i == T)
      {// 尾部
         p->next = head;
         head->pre = p;
      }
      if (pre != NULL)
      {// 双向相连
         pre->next = p;
         p->pre = pre;
      }
      pre = p;
   } 
   joseplus(head,1);
   //test_log_list(head,head);
}

int test_log_list(struct Person* head,struct Person* current)
{
  if (current->next == head) 
  {
     printf("%d\n",current->number);
     printf("链接末尾\n");
     return -1;
  }

  printf("%d\n",current->number);
  
  return test_log_list(head,current->next);
}

//时间复杂度O(M的T-1次方)
int joseplus(struct Person* current,int call) 
{
  
   if(call == M)
   {//喊到对应的M则进行移除
      current->pre->next = current->next;
      current->next->pre = current->pre;
      call = 0;
      free(current);
   }
   if (current->next == current && current->pre == current)
   {//只剩下最后一个
      printf("最后一个为:%d\n",current->number);
      return current->number;
   }
   return joseplus(current->next,++call);
}
